import React, { useState, useRef } from 'react';
import { Button, Modal, Upload, message } from 'antd';
import { headUpload, mainImgPathUpload } from '../../services';
import { getCroppedImg } from '../../utils';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import './index.less';
import { TextWidget, getMessage } from '@inbiz/react';
import { useDebounceFunc } from '@inbiz/hooks';
const prefixCls = 'inbiz-ImageCropBox'; // 组件通用样式
const TEAM_FILE = 'newFile.png'; // 头像裁剪 预览临时文件
const IMAGE_TYPE_LIST = ['image/jpg', 'image/jpeg', 'image/png', 'image/bmp']; // 上传文件类型

export interface ImageCropProps {
  visible?: boolean; // 展示隐藏
  imgSource?: string; // 文件base64流
  onCancel?: () => any; // 取消
  onSubmit?: () => any; // 提交保存
}

const ImageCrop: React.FC<ImageCropProps> = (props) => {
  const { visible, onCancel, onSubmit, imgSource } = props;
  const [crop, $setCrop] = useState<any>();
  const [croppedImageUrl, $setCroppedImageUrl] = useState<any>();
  const [aspect, $setAspect] = useState<number | undefined>(16 / 9);
  const [Base64Source, $setImgSource] = useState<any>(imgSource);
  const [reloading, $setReloading] = useState(false);
  const [loading, $setLoding] = useState(false);
  const [mainImgPath, $setMainImgPath] = useState();

  const imgRef = useRef<HTMLImageElement>(null);

  // 触发裁剪预览
  const makeClientCrop = async (crop: any) => {
    if (imgRef.current && crop.width && crop.height) {
      const croppedImageUrl = await getCroppedImg(imgRef.current, crop, TEAM_FILE);
      $setCroppedImageUrl(croppedImageUrl);
    }
  };

  // 头像原图加载完成 设置默认裁剪坐标及触发预览
  const onImageLoad = (e: React.SyntheticEvent<HTMLImageElement>) => {
    if (aspect) {
      const { width, height } = e.currentTarget;
      if (width && height) {
        const cropValue = { x: 0, y: 0, width, height, unit: 'px' };
        $setCrop(cropValue);
        makeClientCrop(cropValue);
      }
    }
  };

  // 上传类型/大小判断
  const onImgFilesChange = async (info: any) => {
    const file = info.file;

    if (IMAGE_TYPE_LIST.indexOf(file.type) < 0) {
      return message.warn(getMessage('personalInfo.imgLimit'));
    }
    if (file.size > 5 * Math.pow(2, 20)) {
      message.error(getMessage('personalInfo.topsfiveM'));
      return;
    }
    uploadImg(file);
  };

  // 重新上传
  const uploadImg = async (file: any) => {
    const formData = new FormData();
    formData.append('imgHead', file);
    $setReloading(true);
    try {
      const res = await headUpload(formData);
      $setReloading(false);
      if (res.path) {
        $setImgSource(res.path);
        $setMainImgPath(res.path);
      } else {
        message.warning(getMessage('personalInfo.uploadFailed'));
      }
    } catch (e) {
      $setReloading(false);
      message.warning(getMessage('personalInfo.uploadFailed'));
    }
  };

  // 裁剪后确认提交
  const uploadMiniImg = async () => {
    if (!mainImgPath) {
      onCancel && onCancel();
      return false;
    }
    const formData = new FormData();
    formData.append('mainImgPath', Base64Source);
    formData.append('imgY', parseInt(crop.y));
    formData.append('imgX', parseInt(crop.x));
    formData.append('imgWidth', parseInt(crop.width));
    formData.append('imgHeight', parseInt(crop.height));
    formData.append('resetChoose', true);
    $setLoding(true);
    try {
      const res = await mainImgPathUpload(formData);
      $setLoding(false);
      if (res.ok) {
        message.success(getMessage('personalInfo.editSuccess'));
        onSubmit && onSubmit();
      } else {
        message.warning(getMessage('personalInfo.editFailed'));
      }
    } catch (e) {
      $setLoding(false);
      message.warning(getMessage('personalInfo.editFailed'));
    }
  };

  const _makeClientCrop = useDebounceFunc((c: any) => {
    makeClientCrop(c);
  })

  const ContentView = () => {
    return (
      <div className={`${prefixCls}`}>
        <div className={`${prefixCls}-upload-tips`}>
          <TextWidget>personalInfo.imgTips</TextWidget>
        </div>
        <div className={`${prefixCls}-view`}>
          <div className={`${prefixCls}-view-left`}>
            <ReactCrop
              crop={crop}
              onChange={(c) => {
                $setCrop(c);
                _makeClientCrop(c);
              }}
            >
              <img
                ref={imgRef}
                width={`100%`}
                height={`auto`}
                src={Base64Source}
                crossOrigin="anonymous"
                onLoad={onImageLoad}
              />
            </ReactCrop>
          </div>
          <div className={`${prefixCls}-view-right`}>
            <div className={`${prefixCls}-view-imgbox-l`}>
              <img src={croppedImageUrl}></img>
              <p>
                <TextWidget>personalInfo.bigAvatar</TextWidget>
              </p>
            </div>
            <div className={`${prefixCls}-view-imgbox-m`}>
              <img src={croppedImageUrl}></img>
              <p>
                <TextWidget>personalInfo.mediumAvatar</TextWidget>
              </p>
            </div>
            <div className={`${prefixCls}-view-imgbox-s`}>
              <img src={croppedImageUrl}></img>
              <p>
                <TextWidget>personalInfo.smallavatar</TextWidget>
              </p>
            </div>
          </div>
        </div>
        <div className={`${prefixCls}-footer`} style={{ display: 'flex' }}>
          <div style={{ flex: 1 }}>
            <Upload customRequest={onImgFilesChange} name={`file`} showUploadList={false}>
              <Button type="primary" loading={reloading}>
                <TextWidget>personalInfo.reselect</TextWidget>
              </Button>
            </Upload>
          </div>
          <Button onClick={onCancel} style={{ marginRight: 10 }}>
            <TextWidget>global.cancel</TextWidget>
          </Button>
          <Button type="primary" loading={loading} onClick={() => uploadMiniImg()}>
            <TextWidget>global.save</TextWidget>
          </Button>
        </div>
      </div>
    );
  };

  return (
    <Modal
      footer={null}
      title={getMessage('personalInfo.addAvatar')}
      visible={visible}
      width={698}
      onOk={onSubmit}
      onCancel={onCancel}
      bodyStyle={{ padding: `0 20px 20px 20px` }}
    >
      {ContentView()}
    </Modal>
  );
};

export default ImageCrop;
